package logutils

import (
	"fmt"
	"github.com/rocknio/RotateLogWriter"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
	"sync"
)

var (
	l           sync.RWMutex
	initialized bool
	Logger      *zap.Logger
	Atom        zap.AtomicLevel
)

func InitLogger() error {
	l.Lock()
	defer l.Unlock()

	if initialized {
		return fmt.Errorf("logger already initialized")
	}

	var level zapcore.Level

	hook := &lumberjack.Logger{
		Filename:       "./log/arc_soft.log", // 日志文件路径
		MaxSize:        100,                  // MB
		Compress:       false,                // 是否压缩
		LocalTime:      true,                 // 是否使用本地时间
		RotateEveryDay: true,
	}
	w := zapcore.AddSync(hook)

	if err := level.UnmarshalText([]byte("info")); err != nil {
		panic(err)
	}
	Atom = zap.NewAtomicLevelAt(level)

	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder

	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		zapcore.NewMultiWriteSyncer(os.Stdout, w),
		Atom,
	)

	Logger = zap.New(core, zap.AddCaller(), zap.AddStacktrace(zap.ErrorLevel))

	initialized = true

	return nil
}

func SetLogLevel(level string) {
	switch level {
	case "debug":
		Atom.SetLevel(zap.DebugLevel)
	case "info":
		Atom.SetLevel(zap.InfoLevel)
	case "warn":
		Atom.SetLevel(zap.WarnLevel)
	case "error":
		Atom.SetLevel(zap.ErrorLevel)
	case "panic":
		Atom.SetLevel(zap.PanicLevel)
	case "fatal":
		Atom.SetLevel(zap.FatalLevel)
	default:
		Atom.SetLevel(zap.InfoLevel)
	}
}
